<template>
  <div>
    <div class="block">
      <el-tree
        ref="tree"
        :data="treeData"
        show-checkbox
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :render-content="renderContent"
        :row-style="{height:'40px'}"
        :cell-style="{padding:'40px'}"
      >
          <!--<span slot-scope="{node, data}">
              <span>{{data.nameEn}}</span>
          </span>-->
      </el-tree>
    </div>
  </div>
</template>

<script>

import { getAuthsTree, getMyAuthsByRoleId, saveMyAuthsByRoleId } from './api/auth'

export default {
  props: {
    role: Object,
    closeDialog: Function
  },
  data() {
    return {
        dataLimitModel: {},
        menuIdList:[], // checked menu id list
        treeData: [],
    }
  },
  watch: {
    role: {
      immediate: true, // 这句重要
      handler(role) {
        this.checkedAuths(role.id)
      }
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getAuthsTree().then(result => {
          this.treeData = result.map.list
          setTimeout(() => {
              this.changeCss()
          })
      })
    },

    checkedAuths(roleId) {
        this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys([])
            this.dataLimitModel = {}
        })
        getMyAuthsByRoleId({ roleId: roleId }).then(result => {
            let data = result.map.menu4RoleConfByRoleIdJson
            data = JSON.parse(data)
            this.menuIdList = []
            let json = {}
            data.forEach((menu, index) => {
                this.menuIdList[index] = menu.menuId
                json['d_'+menu.menuId] = ''+menu.dataLimitType
            })
            // 要重新赋值，不然vue不生效，无法修改select值
            this.dataLimitModel = json
            this.$nextTick(() => {
                this.$refs.tree.setCheckedKeys(this.menuIdList)
            })
        })
    },

    saveAuths() {
        // console.log(this.dataLimitModel)
        // 取子节点ID
        const menuIdArr = []
        const nodes = this.$refs.tree.getCheckedNodes()
        nodes.forEach((node) => {
            if (node.children === undefined) {
                menuIdArr.push(node.id)
            }
        })

        saveMyAuthsByRoleId({ roleId: this.role.id, menuIdArr: menuIdArr.toString(), dataLimitType:JSON.stringify(this.dataLimitModel) }).then(r => {
            this.notify(r)
            if (r.success) {
                this.closeDialog()
            }
        })
    },

    resetChecked() {
      this.$refs.tree.setCheckedKeys([])
    },

    /* append(data) {
      const newChild = { id: id++, label: 'testtest', children: [] }
      if (!data.children) {
        this.$set(data, 'children', [])
      }
      data.children.push(newChild)
    },*/

    remove(node, data) {
      this.changeCss()
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },

    // 内容区渲染后执行 判断底层 赋 class
    renderContent(h, {node, data, store}) {
      let classname = ''
      /*if (node.level === 3 && node.childNodes.length === 0) {
        classname = 'levelname'
      }
      if (node.level === 4 && node.childNodes.length === 0) {
        classname = 'levelname'
      }
      if (node.level === 5 && node.childNodes.length === 0) {
        classname = 'levelname'
      }
      // 由于项目中有二级菜单也有三级菜单，就要在此做出判断。
      if (node.level === 2 && node.childNodes.length === 0) {
        classname = 'levelname'
      }*/
      if (node.childNodes.length === 0)  {
        classname = 'levelname'
      }
      //this.dataLimitModel['d_'+node.id] = '0'
      if (data.auth.indexOf(':query')!==-1) {
          return (
              <p class={classname}>
                  {node.label} &nbsp;
                  <el-select id={'d_'+data.id} v-model={this.dataLimitModel['d_'+data.id]} size="mini" style="width: 130px;" placeholder='全部数据' >
                      <el-option label="全部数据" value="0"></el-option>
                      <el-option label="本机构数据" value="10"></el-option>
                      <el-option label="本人数据" value="20"></el-option>
                  </el-select>
              </p>
          )
      }else {
          return (
              <p class={classname}>
              {node.label}
              </p>)
      }
    },

    changeCss() {
      var levelName = document.getElementsByClassName('levelname') // levelname是上面的最底层节点的名字
      for (var i = 0; i < levelName.length; i++) {
        // cssFloat 兼容 ie6-8  styleFloat 兼容ie9及标准浏览器
        levelName[i].parentNode.style.cssFloat = 'left' // 最底层的节点，包括多选框和名字都让他左浮动
        levelName[i].parentNode.style.styleFloat = 'left'
      }
    }

  }
}
</script>
<style scoped>
/deep/.el-input--mini .el-input__inner {
  height: 24px;
  line-height: 24px;
}
</style>
